<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {applyMusic, createNewAlbum, deleteDraftMusic, listAlbums, listDrafts, listStyles} from "@/api/apply/apply.js";
import { v4 as uuidv4 } from 'uuid';
import OSS from "ali-oss";
import { saveUploadMusicDraft } from "@/api/music/draft/draft.js";
import {getFileExtension} from "@/api/utils.js";

const OSS_PREFIX = 'https://hfymusic.oss-cn-beijing.aliyuncs.com/'
const ossClient = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tFL18o8bX1ZhjUTuQgx',
  accessKeySecret: 'RUCyRoCxgAv8NQQwFNgUynZC6ATjzu',
  bucket: 'hfymusic'
})
const musicList = ref([])
const albumList = ref([])
const AlbumData = ref({
  "name": "",
  "cover":　"",
  "style": "流行",
  "des": "",
  "account": localStorage.getItem('account')
})

const albumId = ref(null)
const showAddAlbum = ref(false)
// 流派数组
const styles = ref([])
function beforeUpload(file) {
  const maxSize = 20 * 1024 * 1024;
  const allowedTypes = ['audio/wav', 'audio/mp3', 'audio/x-m4a', 'audio/mpeg'];
  if (file.size > maxSize) {
    ElMessage.error('音频文件大小必须小于20mb')
    return false;
  }

  console.log(file.type)
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型')
    return false;
  }
  return true;
}

const customUpload = (options) => {
  const {file, onSuccess, onError, onProgress} = options;
  let filename = uuidv4()
  const suffix = getFileExtension(file.name)

  filename = filename + '.' + suffix
  const musicUrl = OSS_PREFIX + 'music/' + `${filename}`
  ossClient.put(`music/${filename}`, file).then((res) => {
    ElMessage.success("上传成功")
    const mediaURL = URL.createObjectURL(file);
    const mediaElement = new Audio(mediaURL);
    const durationInSeconds = mediaElement.duration;

    const newMusic = {
      "musicUrl": musicUrl,
      "name": "",
      "duration": durationInSeconds
    }
    musicList.value.push(newMusic)
    console.log(musicUrl)
    // 发个消息 保存下草稿
    saveUploadMusicDraft(musicUrl,localStorage.getItem('account'))
  }).catch(error => {
    console.error('上传失败:', error);
  })

}
onMounted( () => {

  console.log(uuidv4())
  listAlbums(localStorage.getItem('account')).then((res)=>{
    albumList.value = res.data
  })
  listDrafts(localStorage.getItem('account')).then((res) => {
    musicList.value = res.data
  })
  listStyles().then((res) => {
    styles.value = res.data
  })

})

function delMusic(id, index) {
  deleteDraftMusic(id).then((res)=>{
    musicList.value.splice(index, 1);
    ElMessage.success("删除该记录成功！")
  })
}
function addNewAlbum() {
  showAddAlbum.value = !showAddAlbum.value
}

const loading = ref(0)

const ruleFormRef = ref()
// 创建文件输入元素
let inputElement = null;
function toGetImg() {
  if (!inputElement) {
    inputElement = document.createElement('input');
    inputElement.setAttribute('type', 'file');
    inputElement.style.display = 'none';

    inputElement.addEventListener('change', uploadFile, false);
    document.body.appendChild(inputElement);
  }
  inputElement.click();
}

// 方法：处理文件上传
function uploadFile(event) {
  const files = event.target.files;
  if (files.length <= 0) {
    ElMessage.info('请上传文件')
    return
  }
  const file = files[0];
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!');
  } else if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
      // 读取完成后，将结果赋值给img的src
      AlbumData.value.cover = this.result;
    }
    loading.value = 1;
    // 把图片文件发送给后端服务器 上传到OSS

    let filename = uuidv4()
    const suffix = getFileExtension(file.name)

    filename = filename + '.' + suffix
    const coverUrl = OSS_PREFIX + 'img/' + `${filename}`
    ossClient.put(`music/${filename}`, file).then((res) => {
      AlbumData.value.cover = coverUrl
      loading.value = 0
      ElMessage.success("上传成功")
    }).catch(error => {
      console.error('上传失败:', error);
    })
  }
}

const rules = reactive({
  name: [
    { required: true, message: '请输入专辑名称', trigger: 'blur' },
    { min: 1, max: 15, message: '名字长度必须在1-15之间', trigger: 'blur' },
  ],
  cover: [
    {
      required: true,
      message: '请上传头像',
      trigger: 'change',
    },
  ],
  des: [
    { required: true, message: '简介不能为空', trigger: 'blur' },
    { min: 10, max: 1000, message: '简介长度必须在10-1000字之间', trigger: 'blur' }
  ],
})

const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      createNewAlbum(AlbumData.value.name, AlbumData.value.cover, AlbumData.value.style, AlbumData.value.des, localStorage.getItem('account')).then((res) => {
        ElMessage.success("创建成功！")
        document.location.reload()
      })
    }
    else console.log('错误提交!', fields)

  })
}

function submitTotal() {
  ElMessageBox.confirm(
      '你将要上传审核这个专辑，确定吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
  .then(() => {
    // 这是新建专辑 不需要判断是否有音乐上传
    if (musicList.value.length === 0) {
      ElMessage.error("请至少上传一个音乐")
    } else if (albumId.value === null) {
      // 因为默认值为null，而id又不可能为null，所以为null时 一定没有指定专辑
      ElMessage.error("请指定一个专辑")
    } else {
      // 发一个请求 参数有一个音乐列表 还有一个专辑id
      applyMusic(albumId.value, musicList.value, localStorage.getItem('account')).then((res)=>{
        ElMessage.success("提交审核成功")
        document.location.reload()
      })
    }
  })
  .catch((e) => ElMessage.error(e))
}

let audio = null;
let curMusicUrl = ref('')
function play(musicUrl) {
  // 创建一个音频对象
  audio = new Audio(musicUrl);
  curMusicUrl.value = musicUrl
  // 播放音频
  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }
}
function pause() {
  audio.pause()
  curMusicUrl.value = ''
}

</script>

<template>
  <div class="container">


    <div class="upload">

      <h4>
        <span class="title-bar"></span>
        上传歌曲
        <span style="display: inline-block;margin-left: 10px;font-weight: normal;color: #8c8c8c">
          ( {{ musicList.length }}首 )
        </span>
      </h4>
      <div class="music" v-for="(item, index) in musicList" :key="index">
        <div style="width: 84px;padding-left: 24px;height: 40px;line-height: 40px">曲目{{ index + 1 }}</div>


        <svg v-if="curMusicUrl === item.musicUrl" @click="pause" style="cursor:pointer;margin-right: 22px" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M16 12V36" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M32 12V36" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <svg v-else @click="play(item.musicUrl)" style="cursor:pointer;margin-right: 22px" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M15 24V11.8756L25.5 17.9378L36 24L25.5 30.0622L15 36.1244V24Z" fill="#333" stroke="#333" stroke-width="4" stroke-linejoin="round"/>
        </svg>
        <input v-model="item.name" placeholder="请输入歌曲名称，最多30字" maxlength="30" autocomplete="off" class="name-input">
        <div @click="delMusic(item.id,index)" class="music-del">删除</div>
      </div>


      <el-upload
          drag
          action="#"
          :http-request="customUpload"
          multiple
          accept="audio/wav, audio/mp3, audio/x-m4a, audio/mpeg"
          :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled style="font-size: 40px" /></el-icon>
        <div style="margin-top: -20px">
          <p v-if="musicList.length === 0" style="font-size: 15px;margin-bottom: 5px">点击/将歌曲拖动到此处上传</p>
          <p v-else-if="musicList.length >= 0" style="font-size: 15px">继续上传歌曲</p>
          <p style="color: #999999;font-size: 12px">音频文件大小必须小于20MB</p>

        </div>

      </el-upload>
    </div>

    <div class="upload">

      <h4>
        <span class="title-bar"></span>
        设置原创专辑
      </h4>

      <div class="album-list">
        <div :class="{'album-selected': item.id === albumId}" @click="albumId = item.id" v-for="(item,index) in albumList" :key="index" class="album-item hover">
          <img style="width: 80px;height: 80px;border-radius: 8px" :src="item.cover">
          <div style="padding-top: 10px">{{ item.name }}</div>
        </div>
      </div>


      <div @click="addNewAlbum" style="padding: 30px 0;display: flex;align-items: center;justify-content: center" class="el-upload-dragger">
        <svg style="line-height: 20px;margin-right: 8px" width="14" height="14" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M24 44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C12.9543 4 4 12.9543 4 24C4 35.0457 12.9543 44 24 44Z" fill="#333" stroke="#333" stroke-width="4" stroke-linejoin="round"/><path d="M24 16V32" stroke="#FFF" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 24L32 24" stroke="#FFF" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <span style="font-size: 14px">创建新专辑</span>

      </div>

      <div style="padding: 30px 92px 40px;margin-top: -2px;background: #f8f9fc;" v-if="showAddAlbum">
        <el-form class="form"
                 :model="AlbumData"
                 ref="ruleFormRef"
                 :rules="rules"
        >
          <el-form-item prop="name" class="row name">
            <div class="span">专辑名称</div>

            <input v-model="AlbumData.name" placeholder="请输入专辑名称，最多40个字符" maxlength="40" style="font-size: 12px;background: white!important;width: 370px;padding: 0 15px;line-height: 34px;border: 0;outline: none" >

          </el-form-item>

          <el-form-item prop="cover" class="row avatar">
            <div class="span">专辑封面</div>

            <div style="position: relative;" class="bigImg-div" @click="toGetImg">
              <svg v-if="loading === 1" style="position: absolute;top: 43px;left: 43px" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M24 4V8" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M34 6.6795L32 10.1436" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M41.3203 14L37.8562 16" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M44 24H40" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M41.3203 34L37.8562 32" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M34 41.3205L32 37.8564" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M24 44V40" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 41.3205L16 37.8564" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.67969 34L10.1438 32" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 24H8" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.67969 14L10.1438 16" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 6.6795L16 10.1436" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><animateTransform attributeName="transform" type="rotate" from="0 0 0" to="360 0 0" dur="2.2s" repeatCount="indefinite" /></svg>
              <img v-if="AlbumData.cover" class="bigImg" :src=AlbumData.cover>
              <img v-else class="bigImg" src="@/assets/img/icon.png">

              <div style="margin-left: 30px;display: flex;align-items: center;gap: 4px">
                <img style="line-height: 110px;width: 25px;height: 14px" src="@/assets/img/upload/upload.png">
                <span style="font-size: 11px;color: #e96161">上传</span>
              </div>
            </div>
          </el-form-item>



          <el-form-item class="row type" >
            <div class="span">流派</div>
            <el-select
                type="default"
                v-model="AlbumData.style"
                style="width: 360px"
                class="select"
            >
              <el-option style="font-size: 12px;"

                         v-for="item in styles"
                         :key="item.id"
                         :label="item.title"
                         :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item required style="position: relative;" class="row brief" prop="des">
            <div style="position: absolute;top: 0" class="span">简介</div>
            <textarea placeholder="请输入10-1000字" v-model="AlbumData.des" minlength="10" maxlength="1000" class="brief-textarea"></textarea>
          </el-form-item>

          <div @click="submit(ruleFormRef)" class="btn">新建歌单</div>

        </el-form>
      </div>

    </div>


    <div @click="submitTotal" class="btn">提交审核</div>


</div>
</template>

<style scoped>

.album-list {

}
.album-item {
  display: flex!important;
  margin: 15px 0;
  font-family: 微軟正黑體;
  font-style: italic;
  font-weight: bold;
  font-size: 20px;
  gap: 25px;
  cursor: pointer;
  border-radius: 10px;
  padding: 4px;
}
.album-item:hover {
  background: #f5fbff;
  color: #e96161;
}
.album-selected {
  color: #e96161!important;
  background: #e3f4ff;
}
.btn {
  margin-top: 30px;
  margin-left: 50%;
  transform: translateX(-50%);
  cursor: pointer;
  z-index: 6;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 40px;
  color: white;
  font-size: 16px;
  padding: 12px 20px;
  border-radius: 68px;
  background: #ff8457;
  box-sizing: border-box;
  font-family: poppin,Tahoma,Arial,\5FAE\8F6F\96C5\9ED1,sans-serif;
}

.bigImg-div {
  width: 210px;
  cursor: pointer;
  height: 110px;
  display: flex;
  background: white;
}

.bigImg {
  display: block;
  width: 110px;
  height: 110px;
  border-radius: 4px;
}

.row {
  display: flex;
  font-size: 13px;
  margin-top: 30px;
}
.span {
  width: 120px;
}
.brief-textarea {
  margin-left: 120px;
  border: 0;
  outline: none;
  padding: 14px 28px;
  border-radius: 8px;
  resize: vertical;
  background: white;
  min-height: 46px;
  width: 500px;
  box-sizing: border-box;
  height: 100px;
  font-size: 12px;
  max-height: 250px;
  font-family: "pingfang SC", poppin, Arial, 微软雅黑, sans-serif;
  color: rgba(0, 0, 0, .65)!important;
}
.avatar>span {
  line-height: 110px;
}

.is-selected {
  color: #e96161!important;
}
h4 {
  position: relative;
  font-size: 16px;
  color: #333;
  margin-bottom: 45px;
  right: 30px;
}
.title-bar {
  display: inline-block;
  vertical-align: middle;
  margin-top: -3px;
  width: 4px;
  height: 16px;
  border-radius: 100px;
  background-color: #e96161;
}
.music-del {
  color: #e96161;
  cursor: pointer;
  margin-left: auto;
  margin-right: 30px;
  font-size: 15px;
  width: 30px;
}
.name-input {
  background: white;
  border: 0;
  outline: none;
  padding: 0 15px;
  width: 370px;
  height: 40px;
  line-height: 40px;
}
.upload {
  background: white;
  border-radius: 10px!important;
  padding: 35px 70px;
  margin-bottom: 20px;
}
.music {
  background-color: #f8f9fc;
  display: flex;
  color: rgba(0, 0, 0, .65);
  padding: 12px 0;
  margin-bottom: 24px;
  border-radius: 12px;
  position: relative;
  font-size: 14px;
  line-height: 1.4;
  align-items: center;
}
.music:hover {
  background-color: #f2f4f8;
}
.container {
  padding: 50px 100px 40px 200px;
  font-family: Tahoma, \5fae\8f6f\96c5\9ed1, sans-serif;
}

.el-upload-dragger {
  padding: 0 0 15px;
  background: rgba(233, 97, 97, 0.01)!important;
}
.el-upload-dragger:hover {
  background: #f5f9ff!important;
}
</style>
